package com.bd.scm.module.qywx.thread;

import com.alibaba.fastjson.JSONObject;
import com.bd.scm.domain.models.qywx.TToken;
import com.bd.scm.module.qywx.init.InitServlet;
import com.bd.scm.module.qywx.init.WxInitServlet;
import com.bd.scm.module.utils.WxJSUtil;
import com.bd.scm.module.utils.wx.WXAuthUtil;
import com.bd.utils.wechat.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Observable;

/**
 * 定时获取微信公众号access_token的线程
 *
 * @author YH
 */
public class WxTokenThread extends Observable implements Runnable {
    private static Logger log = LoggerFactory.getLogger(TokenThread.class);

    //获取微信公众凭证url
    public static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WXAuthUtil.APPID+"&secret="+WXAuthUtil.APPSECRET+"";

    //微信公众号凭证
    public static JSONObject jsonObject = null;

    //微信公众号JS凭证
    public static JSONObject ticketJson = null;

    // 此方法一经调用，立马可以通知观察者
    public void doBusiness(){
        if(true){
            super.setChanged();
        }
        notifyObservers();
    }

    @Override
    public void run() {
        while (true) {
            try {
                //微信公众号
                jsonObject = WXAuthUtil.doGetJson(url);
                if (jsonObject.containsKey("access_token")) {
                    TToken token = new TToken();
                    token.setId(UUID.generate());
                    token.setAccessToken(jsonObject.getString("access_token"));
                    token.setExpiresIn(jsonObject.getInteger("expires_in"));
                    token.setAdhibitionName("微信公众号");
                    ticketJson = WxJSUtil.getTicketTool(jsonObject.getString("access_token"));
                    new WxInitServlet().saveToken(token);
                    log.info("获取微信公众号access_token成功，有效时长{}秒 token:{}", jsonObject.getInteger("expires_in"), jsonObject.getString("access_token"));
                    log.info("获取微信公众号ticket成功，有效时长{}秒 token:{}", ticketJson.getInteger("expires_in"), ticketJson.getString("access_token"));
                    System.out.println("获取微信公众号access_token成功，有效时长{"+jsonObject.getString("access_token")+"}秒 token:{"+jsonObject.getString("expires_in")+"}");
                    System.out.println("获取微信公众号ticket成功，有效时长{"+ticketJson.getString("ticket")+"}秒 token:{"+ticketJson.getString("expires_in")+"}");
                    // 休眠7000秒
                    Thread.sleep((jsonObject.getInteger("expires_in") - 200) * 1000);
                } else {
                    log.info("获取微信公众号access_token失败，失败信息{}", jsonObject.toJSONString());
                    // 如果access_token为null，60秒后再获取
                    Thread.sleep(60 * 1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                doBusiness();
                break;
            } catch (Exception e) {
                log.error("https request error:{}", e);
                doBusiness();
                break;
            }
        }
    }
}
